const util = require('./utils/util.js');
const api = require('./api/index.js');
const store = require('./store/index.js')
const {
  //测试环境
  dev,
  //正式环境
  prod
} = require('./utils/url');
const appUtils = require('./utils/app/index');
const pageWatch = require('./utils/app/pageWatch')
import {
  ajaxLogin
} from './api/registerLogin'
// app.js
App({
  globalData: {
    //项目配置
    config: {
      //后台服务请求配置
      server: prod,
      //图片等资源固定请求域名
      baseURL: 'https://k1speed-image.oss-cn-shenzhen.aliyuncs.com/h5'
    },
    //用户信息
    userInfo: null,
    // 语言
    language: 'zhCN',
    //设备信息
    systemInfo: null,
    //是否有网络
    isNetwork: true,
    //自定义导航数据
    customNavInfo: null,
    //用户登入状态
    userLoginState: false,
    //分享页面
    shareUrl: null,
    // 当前店铺信息
    shopInfo: null
  },
  //模块全局状态
  ...store,
  //监听回调页面-数据
  ...pageWatch.data,
  //监听回调页面-方法
  ...pageWatch.methods,
  onLaunch(e) {
    //程序启动参数
    let queryParams = e.query || {};
    //分享页面
    if (queryParams.url) {
      this.globalData.shareUrl = decodeURIComponent(queryParams.url);
    }
    //初始化登入
    this.initLogin().catch(() => {});
    // 非正常路径进入小程序,去首页
    if (!/^pages\/home\/index/g.test(e.path)) {
      //去首页
      wx.switchTab({
        url: `/pages/home/index`
      })
    }
    //检测新版本
    this.isNewVersion();
    //设置设备信息
    this.setSystemInfo();
    //设置自定义顶部导航信息
    this.setCustomNav();
    //监听网络状态
    this.watchNetworkState();
  },
  //封装请求
  api: api,
  ...appUtils.methods,
  // 工具方法
  ...util,
  //初始化登入
  initLogin(loginUserInfo = null) {
    return new Promise(async (resolve, reject) => {
      //本地存储的登入信息
      loginUserInfo = loginUserInfo || wx.getStorageSync('loginUserInfo');
      // 没有登录参数，首页自动跳转到注册登录页面
      if (!loginUserInfo) {
        reject({
          msg: '没有参数'
        });
        return;
      }
      wx.showLoading({
        title: '正在登录',
        mask: true
      })
      try {
        // 获取微信用户的openIdCode
        let openIdCode = await this.getOpenIdCode();
        let {
          data
        } = await ajaxLogin(Object.assign({}, {
          // surnames: loginUserInfo.surnames,
          // name: loginUserInfo.name,
          k1UserId: loginUserInfo.k1UserId,
          tel: loginUserInfo.tel,
          msgCode: loginUserInfo.msgCode || '990105',
          wxCode: openIdCode,
          wxAppId: this.globalData.config.server.APPID,
        }), this);
        this.globalData.userInfo = data
        //登录成功
        this.globalData.userLoginState = true;
        //存储
        wx.setStorageSync('loginUserInfo', this.globalData.userInfo);
        //登录状态通知
        this.runWatchHandle({
          type: "userLoginState",
          data: {
            userLoginState: true
          }
        }, ['homePage', 'orderPage', 'orderingPage', 'myPage']);
        wx.hideLoading();
        resolve(true);
      } catch (err) {
        wx.hideLoading();
        reject(err);
        wx.showToast({
          title: err && err.msg || '网络或系统异常',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  //获取openidCode
  getOpenIdCode() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: res => {
          resolve(res.code);
        },
        fail: err => {
          reject(err);
        }
      });
    })
  },
  // 退出登录
  logOut() {
    wx.removeStorage({
      key: 'loginUserInfo'
    })
    this.globalData.userInfo = null;
    this.globalData.userLoginState = false;
  }
})